//
//  DisPayViewController.m
//  yixintong8127
//
//  Created by longzhiyuan on 15/5/4.
//
//

#import "DisPayViewController.h"
#import "ItemCell.h"
#import "ChildCell.h"
#import "ChildInputCell.h"
#import "GDataXMLNode.h"
#import "GlobalVar.h"
#import "CellDelegate.h"
#import "FootInfoCell.h"
//
@interface DisPayViewController ()<UITableViewDataSource,UITableViewDelegate,CellDelegate>

@property (nonatomic,retain)GDataXMLDocument *xml ;
@property (assign)BOOL blnOpen;
@property (nonatomic,retain) NSIndexPath* selectIndex;
@property (nonatomic,retain)UIView *maskView;
@end

@implementation DisPayViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.title = @"账户充值";
    self.blnOpen = NO;
    NSString *testXMLString = @"<root><item icon='yaloeka' name ='#充值卡' CellId='ItemCell' height='40' title='' info='' ><child CellId='ChildInputCell' height='190' footHeight='72' info='品牌充值卡' >此卡为#公司独家发行，只能为#账户充值，支持任意长度的序列号和密码。\n\n注：所有卡输入成功后，请等待3-5分钟后查询余额。充值无异议后，请再丢弃充值卡。</child></item>@1@2</root>";
    NSString* isThirdChongzhiStr=[[NSUserDefaults standardUserDefaults]objectForKey:@"recStr"];
    int thirdBrandCode=[isThirdChongzhiStr intValue];
    //thirdBrandCode=1;
    if (thirdBrandCode==1)
    {
        NSString *thirdBrand = @"<item icon='ka_icon_14' name ='移动充值卡' CellId='ItemCell' height='40' info=''><child CellId='ChildInputCell' height='190' footHeight='72' info='移动充值卡' >此卡为中国移动公司发行的神州行全国卡，卡号17位，密码18位。\n\n注：所有卡输入成功后，请等待3-5分钟后查询余额。充值无异议后，请再丢弃充值卡。</child></item><item icon='ka_icon_15' name ='联通充值卡' CellId='ItemCell' height='40' info=''><child CellId='ChildInputCell' height='190' footHeight='72' info='联通充值卡' >此卡为中国联通公司发行的联通一卡通卡，卡号15位，密码19位。\n\n注：所有卡输入成功后，请等待3-5分钟后查询余额。充值无异议后，请再丢弃充值卡。</child></item><item icon='ka_icon_3' name ='电信充值卡' CellId='ItemCell' height='40' info=''><child CellId='ChildInputCell' height='190' footHeight='72' info='电信充值卡' >此卡为中国电信公司发行，卡号19位，密码18位，卡号的第4位为1。\n\n注：所有卡输入成功后，请等待3-5分钟后查询余额。充值无异议后，请再丢弃充值卡。</child></item>";
        testXMLString = [testXMLString stringByReplacingOccurrencesOfString:@"@1" withString:thirdBrand];
    }else
    {
        testXMLString = [testXMLString stringByReplacingOccurrencesOfString:@"@1" withString:@""];
    }
    NSString* openFlowCode=[[NSUserDefaults standardUserDefaults]objectForKey:@"openFlow"];
    int intPowerCode = [openFlowCode intValue];
    if (intPowerCode==1)
    {
        NSString *nsStrPower1 = @"<item icon='yaloeka' name ='流量充值' CellId='ItemCell' height='40' title='' info=''><child CellId='ChildInputCell' height='260' footHeight='140' info='流量充值'>温馨提示：\n一、首次充值的号码，请先致电运营商，咨询能否使用流量叠加包;\n二、为保证账户安全，只能给绑定号码充值流量；\n三、充值成功前，请勿将充值卡丢弃；\n四、充值成功后，充值流量于24小时内到账，充值卡将失效；\n五、充值流量和原号码套餐捆绑，自月结日清零(全球通为自然月清零);\n六、此功能为软件增值服务。</child></item>";
        testXMLString = [testXMLString stringByReplacingOccurrencesOfString:@"@2" withString:nsStrPower1];
    }else
    {
        testXMLString = [testXMLString stringByReplacingOccurrencesOfString:@"@2" withString:@""];
    }
    //NSLog(@"testXMLString===%@",testXMLString);
    NSData *xmlData = [testXMLString dataUsingEncoding:NSUTF8StringEncoding];
    //使用NSData对象初始化
    self.xml = [[GDataXMLDocument alloc] initWithData:xmlData  options:0 error:nil];
    //创建节点
    /*
    GDataXMLElement *element = [self createItemElement:@"ItemCell" name:@"兑换流量"];
    [element addChild:[self createChild:@"ChildCell" value:@"" info:@"20_title" height:@"40"]];
    [element addChild:[self createChild:@"FootInfoCell" value:@"" info:@"温馨提示：\n一、首次兑换流量的号码，请先致电运营商，咨询能否使用流量叠加包；\n二、为保证账户安全，只能给绑定号码兑换流量；\n三、一经兑换，话费余额立即扣除，不作退还；\n四、兑换的流量和原号码套餐捆绑，自结算日清零；\n五、此功能为软件增值服务。" height:@"120"]];
    [self.xml.rootElement addChild:element];
     */
    
    NSString* changeFlow=[[NSUserDefaults standardUserDefaults]objectForKey:@"changeFlow"];
    int changeFlowCode = [changeFlow intValue];
    if (changeFlowCode==1)
    {
        //type 类型，比如：中国移动、中国电信、中国联通，分别是：0,1,2
        [self getLiuliangList:[GlobalVar getTypeByPhoneNumber]];
    }
    
}
-(GDataXMLElement*)createItemElement:(NSString*)iconId name:(NSString*)name
{
    GDataXMLElement *element = [GDataXMLNode elementWithName:@"item"];
    //创建属性
    [element addAttribute:[self createAttribute:@"icon" value:@"yaloeka"]];
    [element addAttribute:[self createAttribute:@"name" value:name]];
    [element addAttribute:[self createAttribute:@"CellId" value:iconId]];
    [element addAttribute:[self createAttribute:@"height" value:@"40"]];
    [element addAttribute:[self createAttribute:@"title" value:@""]];//兑换流量
    return element;
}
-(GDataXMLElement*)createChild:(NSString*)cellId value:(NSString*)value info:(NSString*)info height:(NSString*)height;
{
    GDataXMLElement *element = [GDataXMLNode elementWithName:@"child" stringValue:value];
    [element addAttribute:[self createAttribute:@"CellId" value:cellId]];
    [element addAttribute:[self createAttribute:@"height" value:height]];
    [element addAttribute:[self createAttribute:@"footHeight" value:@"140"]];
    [element addAttribute:[self createAttribute:@"info" value:info]];
    return element;
}
-(GDataXMLElement*)createAttribute:(NSString*)name value:(NSString*)value
{
    return [GDataXMLNode attributeWithName:name stringValue:value];
}
-(void)viewWillAppear:(BOOL)animated
{
    //[self childInputCellQequestFail];
    [super viewWillAppear:animated];
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
-(void)getLiuliangList:(int)type
{
    NSString* preMd5=[NSString stringWithFormat:@"%d%@%@",type,SOFT_ID,@"ysw"];
    NSString* md5=[GlobalVar md5Str:preMd5];
    ASIFormDataRequest* request=[ASIFormDataRequest requestWithURL:[NSURL URLWithString:@"http://61.146.138.146:8008/lyb/tel/list.php"]];
    [request setTimeOutSeconds:TIME_OUT_SECONDS];
    [request setDelegate:self];
    [request setPostValue:[NSString stringWithFormat:@"%d",type] forKey:@"type"];
    [request setPostValue:SOFT_ID forKey:@"softId"];
    [request setPostValue:md5 forKey:@"md5"];
    [request setDidFinishSelector:@selector(getLiuliangListSuccess:)];
    [request setDidFailSelector:@selector(getLiuliangListFail:)];
    [request startAsynchronous];
    
}
#pragma mark获取流量列表回调
-(void)getLiuliangListSuccess:(ASIHTTPRequest*)request
{
    //NSLog(@"返回的流量包列表信息===:%@",[request responseString]);
    NSString* listInfo=[request responseString];
    if ([listInfo length]>0)
    {
        NSArray* infoArr=[listInfo componentsSeparatedByString:@"|"];
        if ([infoArr count]>1)
        {
            int code=[[infoArr objectAtIndex:0] intValue];
            if (code==1)
            {
                //json数据结构
                NSString* infroString=[infoArr objectAtIndex:1];
                NSData *tempData =[infroString dataUsingEncoding:NSUTF8StringEncoding];
                id tempDictionary=[NSJSONSerialization JSONObjectWithData:tempData options:kNilOptions error:nil];
                if([tempDictionary isKindOfClass:[NSArray class]])
                {
                    self.nsArrData =(NSArray *)tempDictionary;
                    //创建节点
                     GDataXMLElement *element = [self createItemElement:@"ItemCell" name:@"兑换流量"];
                    for (int i=0; i< self.nsArrData.count; i++)
                    {
                        NSDictionary *tempDic =[self.nsArrData objectAtIndex:i];
                        NSString* title=[tempDic objectForKey:@"title"];
                        NSString* nsStrId=[tempDic objectForKey:@"id"];
                        title=[NSString stringWithFormat:@"%@_%@",nsStrId,title];
                        [element addChild:[self createChild:@"ChildCell" value:@"" info:title height:@"40"]];
                    }
                    //[element addChild:[self createChild:@"ChildCell" value:@"" info:@"20_title" height:@"40"]];
                    [element addChild:[self createChild:@"FootInfoCell" value:@"" info:@"温馨提示：\n一、首次兑换流量的号码，请先致电运营商，咨询能否使用流量叠加包；\n二、为保证账户安全，只能给绑定号码兑换流量；\n三、一经兑换，话费余额立即扣除，不作退还；\n四、兑换的流量和原号码套餐捆绑，自结算日清零；\n五、此功能为软件增值服务。" height:@"120"]];
                    [self.xml.rootElement addChild:element];
                    [self.tableView reloadData];
                }
                
            }
        }
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *CellId = @"ChildCell";
    NSString *nsStrTitle = @"";
    NSString *nsStrIcon = @"";
    NSString *nsStrType = @"";
    NSString *nsStrFootHeight = @"";
    NSString *nsStrInfo = @"";
    if (indexPath.row==0)
    {
        NSArray *arr0 = [self.xml.rootElement elementsForName:@"item"];
        GDataXMLElement *element = [arr0 objectAtIndex:indexPath.section];
        CellId = [[element attributeForName:@"CellId"]stringValue];
        nsStrTitle = [[element attributeForName:@"name"]stringValue];
        nsStrIcon = [[element attributeForName:@"icon"]stringValue];
    }else
    {
        NSArray *arr0 = [self.xml.rootElement elementsForName:@"item"];
        GDataXMLElement *element = [arr0 objectAtIndex:indexPath.section];
        GDataXMLElement *element0 = [[element elementsForName:@"child"] objectAtIndex:indexPath.row-1];
        CellId = [[element0 attributeForName:@"CellId"]stringValue];
        nsStrType = [[element0 attributeForName:@"info"]stringValue];
        nsStrFootHeight = [[element0 attributeForName:@"footHeight"]stringValue];
        //
        nsStrTitle = [element0 stringValue];
        nsStrInfo = [[element0 attributeForName:@"info"]stringValue];
    }
    nsStrTitle = [nsStrTitle stringByReplacingOccurrencesOfString:@"#" withString:SOFT_NAME];
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellId];
    if (cell==nil)
    {
        NSArray * nib = [[NSBundle mainBundle] loadNibNamed:CellId owner:self options:nil] ;
        cell = [nib objectAtIndex:0];
        if ([[[UIDevice currentDevice]systemVersion]floatValue]>=6.0)
        {
            [cell setRestorationIdentifier:CellId];
        }
        //cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellId];
    }
    if (indexPath.row==0)
    {
        UILabel *lab = (UILabel *)[cell.contentView viewWithTag:1];
        if (lab)
        {
            [lab setText:nsStrTitle];
        }
    }else{
        
        if ([cell isKindOfClass:[ChildInputCell class]])
        {
            ChildInputCell *childInputCell = (ChildInputCell *)cell;
            [childInputCell setDataType:nsStrType];
            childInputCell.delegate = self;
            [childInputCell.labFootInfo setText:nsStrTitle];
            if (nsStrFootHeight.length>0)
            {
                NSInteger footHeight = [nsStrFootHeight integerValue];
                childInputCell.labFootInfo.frame = CGRectMake(childInputCell.labFootInfo.frame.origin.x, childInputCell.labFootInfo.frame.origin.y, childInputCell.labFootInfo.frame.size.width, footHeight);
            }
            NSString *nsStrKeyWord = @"一、首次充值的号码，请先致电运营商，咨询能否使用流量叠加包;";
            [self setLabelColor:childInputCell.labFootInfo keyword:nsStrKeyWord];
        }
        if ([cell isKindOfClass:[ChildCell class]])
        {
            ChildCell *childCell = (ChildCell *)cell;
            NSArray *arr=[nsStrInfo componentsSeparatedByString:@"_"];
            childCell.itemId=arr[0];
            childCell.info=arr[1];
            childCell.lab.text =childCell.info;
            childCell.delegate = self;
        }
        if ([cell isKindOfClass:[FootInfoCell class]])
        {
            FootInfoCell*footInfoCell = (FootInfoCell *)cell;
            footInfoCell.lab.text=nsStrInfo;
            NSString *nsStrKeyWord = @"一、首次兑换流量的号码，请先致电运营商，咨询能否使用流量叠加包；";
            [self setLabelColor:footInfoCell.lab keyword:nsStrKeyWord];
        }
    }
    if (nsStrIcon.length>0)
    {
        cell.imageView.image = [UIImage imageNamed:nsStrIcon];
    }
    return cell;
}
-(void)setLabelColor:(UILabel*)lab keyword:(NSString*)nsStrKeyWord
{
    NSString*nsStrTitle=lab.text;
    NSRange nsRankeyword = [nsStrTitle rangeOfString:nsStrKeyWord];
    if (nsRankeyword.location!=NSNotFound)
    {
        NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:lab.text];
        if ([[[UIDevice currentDevice]systemVersion]floatValue]>=6.0)
        {
            //设置颜色
            [attributedString addAttribute:NSForegroundColorAttributeName value:[UIColor redColor] range:NSMakeRange(nsRankeyword.location,nsRankeyword.length)];
            lab.attributedText = attributedString;
        }
    }
}
-(void)getLiuliangListFail:(ASIHTTPRequest*)request
{
    NSLog(@"===getLiuliangListFail====");
}
#pragma mark - Table view data source

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.xml.rootElement elementsForName:@"item"].count;
}
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    if (self.xml.rootElement)
    {
        NSArray *arr0 = [self.xml.rootElement elementsForName:@"item"];
        GDataXMLElement *element = [arr0 objectAtIndex:section];
        return [[element attributeForName:@"title"]stringValue];
    }
    return @"";
}
-(void)childInputCellQequest:(NSString*)info
{
    if (self.maskView==nil)
    {
        self.maskView = [[UIView alloc]initWithFrame:self.view.bounds];
        self.maskView.backgroundColor = [UIColor grayColor];
        self.maskView.alpha = 0.3;
    }
    HUD = [[[MBProgressHUD alloc] initWithView:self.view]autorelease];
    HUD.removeFromSuperViewOnHide = YES;
    [self.view addSubview:HUD];
    [HUD setLabelText:info];
    [HUD show:YES];
    [self.view addSubview:self.maskView];
}
-(void)childInputCellQequestSuccess
{
    //NSLog(@"===childInputCellQequestSuccess=====");
    [HUD hide:YES];
    [self childInputCellQequestFail];
}
-(void)childInputCellQequestFail
{
    [HUD hide:YES];
    //NSLog(@"===childInputCellQequestFail=====");
    if (self.maskView!=nil)
    {
        [self.maskView removeFromSuperview];
    }
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.blnOpen == YES)
    {
        if (self.selectIndex.section==section)
        {
            NSArray *nsDicItemData = [self.xml.rootElement elementsForName:@"item"];
            GDataXMLElement *element = [nsDicItemData objectAtIndex:section];
            return element.childCount+1;
        }
        
    }
    return 1;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    //NSLog(@"======%d ====%ld",indexPath.section,(long)indexPath.row);
    if (self.xml.rootElement)
    {
        NSString *height = @"30";
        if (indexPath.row==0)
        {
            NSArray *arr0 = [self.xml.rootElement elementsForName:@"item"];
            GDataXMLElement *element = [arr0 objectAtIndex:indexPath.section];
            height = [[element attributeForName:@"height"]stringValue];
        }else
        {
            NSArray *arr0 = [self.xml.rootElement elementsForName:@"item"];
            GDataXMLElement *element = [arr0 objectAtIndex:indexPath.section];
            GDataXMLElement *element0 = [[element elementsForName:@"child"] objectAtIndex:indexPath.row-1];
            height = [[element0 attributeForName:@"height"]stringValue];
        }
        return [height intValue];
    }
    return 30;
}

-(BOOL)tableView:(UITableView *)tableView shouldHighlightRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0||[[self getItemName:indexPath.section] isEqualToString:@"兑换流量"])
    {
        return YES;
    }
    return NO;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row == 0)
    {
        if (self.blnOpen == NO)
        {
            self.selectIndex = indexPath;
            self.blnOpen = YES;
        }else
        {
            if ([indexPath isEqual:self.selectIndex])
            {
                self.blnOpen = NO;
            }else
            {
                self.blnOpen = YES;
                self.selectIndex = indexPath;
            }
        }
       [self.tableView reloadData];
    }
    /*
    if([[self getItemName:indexPath.section] isEqualToString:@"兑换流量"])
    {
        NSLog(@"===adsf====%d",indexPath.row);
    }
    */

}
-(NSString*)getItemName:(NSInteger)index
{
    NSArray *arr0 = [self.xml.rootElement elementsForName:@"item"];
    GDataXMLElement *element = [arr0 objectAtIndex:index];
    NSString*name = [[element attributeForName:@"name"]stringValue];
    return name;
}


- (void)dealloc
{

    [super dealloc];
}
- (void)viewDidUnload {
    [self setTableView:nil];
    [self setTableView:nil];
    [super viewDidUnload];
}
@end
